package com.youdianstar.app.ui.account

import android.content.Context
import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.youdianstar.app.R
import com.youdianstar.app.entity.CodeEntity
import com.youdianstar.app.entity.CodeListRes
import com.youdianstar.app.entity.CountryData
import com.youdianstar.app.support.ApiRepository
import com.youdianstar.app.util.CodeComparator
import com.youdianstar.app.common.base.BaseViewModel
import com.youdianstar.app.common.bind.command.BindingAction
import com.youdianstar.app.common.bind.command.BindingCommand
import com.youdianstar.app.common.event.EventLiveData
import com.youdianstar.app.common.event.NetStateLiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.ArrayList


/**
 * File: PhoneCodeViewModel
 * Author: 82149 Create: 2021/9/27 10:18
 * Changes (from 2021/9/27)
 * --------------------------------------------------
 * description: 国家/地区码
 * ---------------------------------------------------
 *
 */
class PhoneCodeViewModel(private val repo: ApiRepository) : BaseViewModel() {

    val finishAction = BindingCommand<Any>(BindingAction {
        finish()
    })
    private val mComparator: CodeComparator by lazy { CodeComparator() }

    val mPhoneCodeLiveData = NetStateLiveData<CodeListRes>()

    //原国家数据
    private val allList: MutableList<CodeEntity> = mutableListOf()
    private val hotList: MutableList<CodeEntity> = mutableListOf()
    //适配数据
    private val listCountry: MutableList<CodeEntity> = mutableListOf()
    private val searchCountry: MutableList<CodeEntity> = mutableListOf()
    val phoneCodeAdapterData = EventLiveData<List<CodeEntity>>()

    /*获取国家码 - 使用本地数据*/
    fun getPhoneCodeData() {
        // 使用本地数据，不再调用接口
        loadLocalData()
    }
    
    /**
     * 加载本地国家数据
     */
    private fun loadLocalData() {
        listCountry.clear()
        listCountry.addAll(CountryData.DEFAULT_COUNTRIES)
        println("PhoneCodeViewModel: 加载了 ${listCountry.size} 个国家数据")
        phoneCodeAdapterData.postValue(listCountry)
    }

    /**
     * 处理接口返回数据
     * @param it CodeListRes 接口数据
     */
    fun loadData(mContext: Context,it: CodeListRes) {
        if (it.hotCountry.isNotEmpty())
            hotList.addAll(it.hotCountry)
        for (data in hotList.withIndex()) {
            val title = if (data.index == 0) mContext.getString(R.string.login_hot) else "-"
            data.value.title = title
        }
        if (it.allCountry.isNotEmpty())
            allList.addAll(parseData(mContext,it.allCountry,it.hotCountry.isNotEmpty()))

        listCountry.clear()
        listCountry.addAll(hotList)
        listCountry.addAll(allList)
        phoneCodeAdapterData.postValue(listCountry)
    }


    /**
     * 筛选处理 - 在本地数据中搜索
     * @param filter 筛选关键字
     */
    fun findSearch(mContext: Context, filter: String) {
        if (CountryData.DEFAULT_COUNTRIES.isEmpty() || filter == "+") {
            phoneCodeAdapterData.value = listOf()
            return
        }

        val filterDateList: MutableList<CodeEntity> = ArrayList()
        if (TextUtils.isEmpty(filter) || filter == "(" || filter == ")") {
            filterDateList.addAll(listCountry) //置空了,显示原列表
        } else {
            searchCountry.clear()
            for (sortModel in CountryData.DEFAULT_COUNTRIES) {
                //小写判断 - 搜索国家名称和代码
                val name = "${sortModel.code}${sortModel.en}${sortModel.cn}"
                if (name.lowercase(Locale.ROOT).contains(filter.lowercase(Locale.ROOT))) {
                    searchCountry.add(sortModel)
                }
            }
            filterDateList.addAll(searchCountry)
        }

        phoneCodeAdapterData.value = filterDateList
    }

    //给数据进行排序
    private fun parseData(mContext: Context,list: List<CodeEntity>, isSortAll:Boolean = true): MutableList<CodeEntity> {
        val tempList: MutableList<CodeEntity> = ArrayList()
        tempList.addAll(list)
        Collections.sort(tempList, mComparator)
        for (data in tempList.withIndex()) {
            var titleStr = "-"
            if (isSortAll && data.index == 0){
                titleStr = mContext.getString(R.string.login_others)
            }
            data.value.title = titleStr
        }
        return tempList
    }
}